// 死锁
// case_2：两线程各有一把锁，但还想请求对方的锁
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

pthread_mutex_t g_lock1;
pthread_mutex_t g_lock2;

void* pthread_start_A(void* arg)
{
    pthread_mutex_lock(&g_lock1);
    sleep(1);
    pthread_mutex_lock(&g_lock2);

    printf("i am pthread A\n");

    pthread_mutex_unlock(&g_lock1);
    pthread_mutex_unlock(&g_lock2);
}

void* pthread_start_B(void* arg)
{
    pthread_mutex_lock(&g_lock2);
    sleep(1);
    pthread_mutex_lock(&g_lock1);

    printf("i am pthread B\n");

    pthread_mutex_unlock(&g_lock2);
    pthread_mutex_unlock(&g_lock1);
}

int main()
{
    pthread_mutex_init(&g_lock1, NULL);
    pthread_mutex_init(&g_lock2, NULL);

    pthread_t A;
    pthread_t B;

    int ret = pthread_create(&A, NULL, pthread_start_A, NULL);
    if(ret < 0)
    {
        perror("pthread_create_A");
    }
    ret = pthread_create(&B, NULL, pthread_start_B, NULL);
    if(ret < 0)
    {
        perror("pthread_create_B");
    }

    pthread_join(A, NULL);
    pthread_join(B, NULL);

    pthread_mutex_destroy(&g_lock1);
    pthread_mutex_destroy(&g_lock2);

    return 0;
}
